package com.jckj.core.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jckj.core.annotation.CurrentDataSource;
import com.jckj.core.contants.SysContants;
import com.jckj.core.dao.OfficeUserMapper;
import com.jckj.core.dao.OfficeUserViewMapper;
import com.jckj.core.dao.SysUserMapper;
import com.jckj.core.dao.UserPermissionViewMapper;
import com.jckj.core.db.DataSourceEnum;
import com.jckj.core.entity.*;
import com.jckj.core.enums.UserStatus;
import com.jckj.core.enums.UserType;
import com.jckj.core.exception.ServiceException;
import com.jckj.core.service.UserService;
import com.jckj.core.util.MyUtils;
import com.jckj.core.util.StringUtils;
import com.jckj.core.vos.OfficeUserQueryVo;
import com.jckj.core.vos.OfficeUserVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * @author liuzhiyuan
 */
@Service
@Transactional(readOnly = true, rollbackFor = ServiceException.class)
public class UserServiceImpl implements UserService {

    private static Logger LOGGER = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private SysUserMapper sysUserMapper;

    @Autowired
    private UserPermissionViewMapper userPermissionViewMapper;

    @Autowired
    private OfficeUserMapper officeUserMapper;

    @Autowired
    private OfficeUserViewMapper officeUserViewMapper;


    @Override
    @CurrentDataSource(DataSourceEnum.SLAVE)
    public SysUser findById(String id) {
        return sysUserMapper.selectByPrimaryKey(id);
    }

    @Override
    @CurrentDataSource(DataSourceEnum.SLAVE)
    public SysUser findByLoginUsername(String loginUsername) {
        MyUtils.setJumpFlag(true);
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andLoginNameEqualTo(loginUsername);
        List<SysUser> sysUserList = sysUserMapper.selectByExample(example);
        if (sysUserList.size() != 1) {
            return null;
        }
        return sysUserList.get(0);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = ServiceException.class)
    @CurrentDataSource(DataSourceEnum.SLAVE)
    public List<String> findUserPermission(String loginUsername) {
        UserPermissionViewExample example = new UserPermissionViewExample();
        UserPermissionViewExample.Criteria criteria = example.createCriteria();
        List<UserPermissionView> userPermissionViews = userPermissionViewMapper.selectByExample(example);
        List<String> permissions = new ArrayList<>();
        for (UserPermissionView obj : userPermissionViews) {
            permissions.add(obj.getPerCode());
        }
        return permissions;
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = ServiceException.class)
    public void addOfficeUser(SysUser sysUser, OfficeUserKey officeUserKey) {
        try {
            sysUserMapper.insert(sysUser);
            officeUserMapper.insert(officeUserKey);
        } catch (Exception ex) {
            LOGGER.error("保存科室人员时发生错误：", ex.fillInStackTrace());
            throw new ServiceException("保存科室人员时发生错误", ex);
        }
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = ServiceException.class)
    public int lockUser(String id) {
        int effectCount = 0;
        try {
            SysUser sysUser = new SysUser();
            sysUser.setId(id);
            sysUser.setUserStatus(UserStatus.LOCKED.getCode());
            effectCount = sysUserMapper.updateByPrimaryKeySelective(sysUser);
        } catch (Exception ex) {
            LOGGER.error("锁定人员信息:", ex.fillInStackTrace());
        }
        return effectCount;
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = ServiceException.class)
    public void resetPassword(OfficeUserVo officeUserVo) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(officeUserVo.getUserId());
        if (sysUser == null) {
            throw new ServiceException("要操作的用户不存在");
        }
        SysUser udpateUser = new SysUser();
        udpateUser.setUpdateTime(officeUserVo.getUpdateTime());
        udpateUser.setUpdateBy(officeUserVo.getUpdateBy());
        udpateUser.setId(officeUserVo.getUserId());
        udpateUser.setPassword(StringUtils.encryPassword(SysContants.DEFAULT_PASSWORD, sysUser.getSalt()));
        sysUserMapper.updateByPrimaryKeySelective(udpateUser);
    }

    @Override
    @CurrentDataSource(DataSourceEnum.SLAVE)
    public long checkUserLoginName(String userLoginName) throws ServiceException {
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andLoginNameEqualTo(userLoginName);
        return sysUserMapper.countByExample(example);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = ServiceException.class)
    public int changeOffice(String userId, String officeId) throws ServiceException {
        int effectCount = 0;
        try {
            OfficeUserExample example = new OfficeUserExample();
            OfficeUserExample.Criteria criteria = example.createCriteria();
            criteria.andUserIdEqualTo(userId);
            officeUserMapper.deleteByExample(example);
            OfficeUserKey officeUser = new OfficeUserKey();
            officeUser.setUserId(userId);
            officeUser.setOfficeId(officeId);
            effectCount = officeUserMapper.insert(officeUser);
        } catch (Exception ex) {
            LOGGER.error("变更科室：", ex);
            throw new ServiceException(ex);
        }
        return effectCount;
    }

    /**
     * 查询办公室人员
     *
     * @return
     */
    @Override
    @CurrentDataSource(DataSourceEnum.SLAVE)
    public List<SysUser> findOfficeWorker() {
        SysUserExample example = new SysUserExample();
        SysUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserTypeEqualTo(UserType.OFFICER.getCode());
        return sysUserMapper.selectByExample(example);
    }


    @Override
    @CurrentDataSource(DataSourceEnum.SLAVE)
    public PageInfo<OfficeUserView> getOfficeUserList(OfficeUserQueryVo officeUserQueryVo) {
        OfficeUserViewExample example = new OfficeUserViewExample();
        OfficeUserViewExample.Criteria criteria = example.createCriteria();
        if(StringUtils.isNotEmpty(officeUserQueryVo.getLoginName())){
            criteria.andLoginNameLike(officeUserQueryVo.getLoginName());
        }
        if(StringUtils.isNotEmpty(officeUserQueryVo.getUsername())){
            criteria.andLoginNameLike(officeUserQueryVo.getUsername());
        }
        if(StringUtils.isNotEmpty(officeUserQueryVo.getOfficeId())){
            criteria.andOfficeIdEqualTo(officeUserQueryVo.getOfficeId());
        }
        Page<OfficeUserView> page = PageHelper.startPage(officeUserQueryVo.getPage(), officeUserQueryVo.getLimit());
        List<OfficeUserView> list = officeUserViewMapper.selectByExample(example);
        PageInfo<OfficeUserView> pageInfo = new PageInfo<>(page);
        pageInfo.setList(list);
        return pageInfo;
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = ServiceException.class)
    public void disabledUser(OfficeUserVo officeUserVo) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(officeUserVo.getUserId());
        if (sysUser == null) {
            throw new ServiceException("要操作的用户不存在");
        }
        if (!UserStatus.NORMAL.getCode().equals(sysUser.getUserStatus())) {
            throw new ServiceException("要操作的用户状态不正确");
        }

        SysUser updateUser = new SysUser();
        updateUser.setId(officeUserVo.getUserId());
        updateUser.setUserStatus(UserStatus.LOCKED.getCode());
        updateUser.setUpdateBy(officeUserVo.getUpdateBy());
        updateUser.setUpdateTime(officeUserVo.getUpdateTime());

        sysUserMapper.updateByPrimaryKeySelective(updateUser);

    }

    @Override
    @Transactional(readOnly = false, rollbackFor = ServiceException.class)
    public void enableUser(OfficeUserVo officeUserVo) {
        SysUser sysUser = sysUserMapper.selectByPrimaryKey(officeUserVo.getUserId());
        if (sysUser == null) {
            throw new ServiceException("要操作的用户不存在");
        }
        if (!UserStatus.LOCKED.getCode().equals(sysUser.getUserStatus())) {
            throw new ServiceException("要操作的用户状态不正确");
        }

        SysUser updateUser = new SysUser();
        updateUser.setId(officeUserVo.getUserId());
        updateUser.setUserStatus(UserStatus.NORMAL.getCode());
        updateUser.setUpdateBy(officeUserVo.getUpdateBy());
        updateUser.setUpdateTime(officeUserVo.getUpdateTime());

        sysUserMapper.updateByPrimaryKeySelective(updateUser);
    }

    @Override
    @Transactional(readOnly = false, rollbackFor = ServiceException.class)
    public void updateOfficeUser(OfficeUserVo officeUserVo) {
        SysUser sysUser = new SysUser();
        sysUser.setId(officeUserVo.getUserId());
        sysUser.setUsername(officeUserVo.getUsername());
        sysUser.setPhone(officeUserVo.getPhone());
        sysUser.setUpdateBy(officeUserVo.getUpdateBy());
        sysUser.setUpdateTime(officeUserVo.getUpdateTime());

        OfficeUserExample example = new OfficeUserExample();
        OfficeUserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(officeUserVo.getUserId());

        OfficeUserKey officeUser = new OfficeUserKey();
        officeUser.setUserId(officeUserVo.getUserId());
        officeUser.setOfficeId(officeUserVo.getOfficeId());

        try {
            officeUserMapper.deleteByExample(example);
            officeUserMapper.insert(officeUser);
            sysUserMapper.updateByPrimaryKeySelective(sysUser);
        }catch(Exception ex){
            LOGGER.error("更新人员信息时出现错误", ex.fillInStackTrace());
            throw new ServiceException("更新人员信息时出现错误");
        }
    }


}